package com.since.algorithm.sort;

import java.util.Arrays;

/**
 * Created by Sincerity on 2020/5/14.
 * 描述：八大排序算法 :就是先分组排序,在进行冒泡排序
 * 希尔排序 - 插入排序
 * 1. 交换式的希尔排序{@link #shellSort2(int[])}
 * 2. 插入式的希尔排序{@link #shellSort(int[])}  更优
 * 很明显 插入式明显比交换式的次数执行少很多 其中少了好多元素的赋值操作
 */
class ShellSort {
    public static void main(String[] args) {
        int[] array = {8, 7, 6, 5, 3, 12, 4};
        System.out.println("原数组:" + Arrays.toString(array));
        shellSort(array);
        System.out.println("排序后:" + Arrays.toString(array));
    }

    /**
     * 希尔排序问题 插入式排序
     *
     * @param array 目标数组
     */
    public static void shellSort(int[] array) {
        //第一次 需要把数组分成array/2个组 [8, 7, 6, 4, 3, 5, 1] ==> [156, 495, 2, 16, -45, 982, 23]
        int temp;
        int i, j;
        int gap = array.length / 2;
        while (gap >= 1) {
            //插入排序的经典操作
            for (i = gap; i < array.length; i++) {
                temp = array[i];
                j = i - gap;
                while (j >= 0 && array[j] > temp) {
                    array[j + gap] = array[j];
                    j = j - gap;
                }
                if (j + gap != i)
                    array[j + gap] = temp;
                System.out.println("分成" + gap + "后, 第:" + i + " :次循环 " + Arrays.toString(array));
            }
            gap /= 2;
        }
    }

    /**
     * 希尔排序 交换式
     *
     * @param array 目标数组
     */
    public static void shellSort2(int[] array) {
        int temp;
        for (int gap = array.length / 2; gap > 0; gap /= 2) {
            for (int i = gap; i < array.length; i++) {
                //1. i=3 j=0-3<0 [8, 7, 6, 4, 3, 5, 1] ==>[4, 7, 6, 8, 3, 5, 1]
                //2. i=4 j=1-3<0 [4, 7, 6, 8, 3, 5, 1] ==>[4, 3, 6, 8, 7, 5, 1]
                //3. i=5 j=2-3<0 [4, 3, 6, 8, 7, 5, 1] ==>[4, 7, 5, 8, 3, 6, 1]
                //4. i=6 j=3-3=0 [4, 3, 6, 8, 7, 5, 1] ==>[4, 7, 5, 1, 3, 6, 8]
                //5. i=7 j=4-3>0 [4, 7, 5, 1, 3, 6, 8] ==>[1, 7, 5, 4, 3, 6, 8]
                for (int j = i - gap; j >= 0; j -= gap) {
                    //冒泡排序
                    if (array[j] > array[j + gap]) {
                        temp = array[j];
                        array[j] = array[j + gap];
                        array[j + gap] = temp;
                    }
                    System.out.println("排序" + gap + "后的数组:" + Arrays.toString(array));
                }
            }

//        }
        }
    }
}
